import React, { useContext, useState } from 'react';
import { checkerSource } from '@@/hw-auth/fns/authProvider.ts';
import { sourceData } from '@@/hw-auth/sourceData';
import { authData } from '@@/hw-auth/fns/sourceDataProvider';
import { RouteModal } from '@@/hw-auth/modal';

const HwAuthContext = React.createContext({});

interface AuthModal {
  appKeyList: string[];
  authData: string | null;
  type: number;
}
export const pageAuthChecker = checkerSource();
export const HwAuthRoot: React.FC = ({ children }) => {
  const [change, setChange] = useState<boolean>(true);
  const [localKey, setLocalKey] = useState<string>(sourceData.localKey);
  const init = (data: AuthModal, childRoute?: RouteModal[] | RouteModal) => {
    authData.set(childRoute);
    pageAuthChecker.set(data);
    setChange(!change);
  };

  const upAuth = (data: AuthModal) => {
    pageAuthChecker.up(data);
    setChange(!change);
  };

  const removeAuth = () => {
    pageAuthChecker.remove();
    setChange(!change);
  };

  const getItemRouteLocalName = (data: RouteModal) => {
    const { local, name } = data;
    return local[localKey] || name;
  };

  return (
    <HwAuthContext.Provider
      value={{
        init,
        upAuth,
        removeAuth,
        localKey,
        setLocalKey,
        getItemRouteLocalName,
        pageAuthChecker,
      }}
    >
      {children}
    </HwAuthContext.Provider>
  );
};//全局权限验证
export const useHwAuthControl = () => {
  return useContext(HwAuthContext);
};
